package com.study.studyroom.utils;


import com.study.studyroom.constant.AuthConstant;
import com.study.studyroom.entity.enums.RequestResultEnum;
import com.study.studyroom.entity.exception.GlobalException;

import java.util.Base64;

/**
 * token工具
 */
public class TokenUtil {

    /**
     * 生成token
     * @param roleId 角色名称
     * @param userId 用户ID
     * @return 返回token
     */
    public static String generateToken(String roleId,String userId){
        String format = String.format(AuthConstant.TOKEN_PREFIX, roleId, userId,System.currentTimeMillis()+30*60*1000);
        return Base64.getMimeEncoder().encodeToString(format.getBytes());
    }

    /**
     * 解析token
     * @param token token
     * @return 返回标准格式
     */
    public static String[] analysisToken(String token){
        byte[] decode = Base64.getMimeDecoder().decode(token);
        String loginMessage = new String(decode);
        String[] split = loginMessage.split(AuthConstant.SEPARATOR);
        if (split.length!=4){
            throw new GlobalException(RequestResultEnum.AUTH_FAILED);
        }
        long expiredTime = Long.parseLong(split[3]);
        if (expiredTime<System.currentTimeMillis()){
            throw new GlobalException(RequestResultEnum.LOGIN_EXPIRED);
        }
        return split;
    }

    /**
     * 根据token获取角色ID
     * @param token token
     * @return 角色ID
     */
    public static String getRoleIdByToken(String token){
        return analysisToken(token)[1];
    }

    /**
     * 根据token获取用户ID
     * @param token token
     * @return 用户ID
     */
    public static String getUserIdByToken(String token){
        return analysisToken(token)[2];
    }

}
